import {
  BadGatewayException,
  BadRequestException,
  Body,
  Controller,
  Get,
  Post,
  Put,
  Res,
  UseGuards,
} from '@nestjs/common';
import { UserService } from './user.service';
import { AuthGuard } from '@nestjs/passport';
import { AuthUser, RequireLogin, UserInfo } from '@app/auth';

@Controller()
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get('/wxQrCode')
  async getWxQrCode(@Res() response) {
    const { file, key } = await this.userService.getWxQrCode();
    response.setHeader('Content-Type', 'image/png');
    response.setHeader(
      'Content-Disposition',
      'attachment; filename=qrcode.png',
    );
    response.setHeader('tag-key', key);

    response.send(file);
  }

  @RequireLogin()
  @Post('test')
  async test(@UserInfo() user: AuthUser) {
    return user;
  }

  @Post('codeStatus')
  async codeStatus(@Body() data: { scene: string }) {
    if (!data.scene) {
      throw new BadGatewayException('scene is required');
    }
    return await this.userService.checkTagKey(data.scene);
  }

  @Post('loginWx')
  async loginWx(@Body() data: { code: string; scene: string }) {
    if (!data.code || !data.scene) {
      throw new BadGatewayException('code | scene is required');
    }
    await this.userService.checkTagKey(data.scene);
    const openId = await this.userService.getWxOpenId(data.code);
    let user = await this.userService.getUserByWxId(openId);
    if (!user) {
      user = await this.userService.createUserByWxId(openId);
    }

    return await this.userService.login({ userId: user.id }, data.scene);
  }
}
